﻿using System;
using System.Collections;
using Eneta.Portal.Forum.Core.Domain.Collections;
using Eneta.Portal.Forum.Core.Service.Application;

namespace Eneta.Portal.Forum.Core.Domain.Entities
{
    public class Forum : DomainObject
    {
        // Fields
        private Hashtable _permissions;
        private TopicCollection _topics;

        // Methods
        private Forum()
        {
        }

        public Forum(int categoryId, string name)
        {
            CategoryId = categoryId;
            Name = name;
        }

        public Forum(int id, int categoryId, string name)
        {
            Id = id;
            CategoryId = categoryId;
            Name = name;
        }

        public bool HasAccess(ForumUser user, Permission.Rights rights)
        {
            if (user.IsAdmin)
            {
                return true;
            }
            foreach (Group group in user.Groups)
            {
                Permission permission = Permissions[group.Id] as Permission;
                if ((permission != null) && permission.HasPermission(rights))
                {
                    return true;
                }
            }
            return false;
        }

        public int CategoryId { get; set; }
        public string Description { get; set; }
        public DateTime LastPost { get; set; }

        public Hashtable Permissions
        {
            get
            {
                if (_permissions == null)
                {
                    _permissions = RepositoryRegistry.ForumRepository.GetPermissionsForForum(Id);
                }
                return _permissions;
            }
        }

        public int PostCount { get; set; }
        public int SortOrder { get; set; }
        public int TopicCount { get; set; }

        public TopicCollection Topics
        {
            get
            {
                if (_topics == null)
                {
                    _topics = RepositoryRegistry.TopicRepository.FindByForumId(base.Id);
                }
                return _topics;
            }
        }
    }
}
